import { AbstractButton, Header, Icon, Layout } from "@/components";
import { View, RadioGroup, Radio, Label } from "@tarojs/components";
import { navigateTo } from "@/utils/navigation";
import {
  getUserAddressList,
  setUserDefaultAddress,
  useUserInfo,
} from "@/store/userDataContext";
import { useAuth } from "@/store/authContext";
import { useEffect } from "react";
import { AddressFieldShape } from "@/data/user/userTypes";
import style from "./index.module.scss";
import { useDidShow } from "@tarojs/taro";
import Taro from "@tarojs/taro";

function WeChatCta() {
  return (
    <View className={style["wechat-cta"]}>
      <Icon className={style["wechat"]} type="WeChat" />
      <View>一键获取微信地址</View>
    </View>
  );
}

export default function AddressDetails() {
  const { dispatchAuthAction } = useAuth();
  const { userInfoState, dispatchUserDataAction, requestWechatAddress } =
    useUserInfo();
  const { userData } = userInfoState;
  const deliveryAddress = userInfoState.userData?.userInfo.deliveryAddress;

  useDidShow(() => {
    if (userInfoState.userData) {
      getUserAddressList(dispatchUserDataAction, userData!, {
        authDispatch: dispatchAuthAction,
      });
    }
  });
  useEffect(() => {
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [dispatchUserDataAction]);

  const hasAddresses = deliveryAddress && !!deliveryAddress.length;

  const onDirectToEditClick = (prepopData: AddressFieldShape | null = null) => {
    dispatchUserDataAction({
      type: "ADDRESS_EDIT_SELECT",
      data: prepopData
        ? {
            ...prepopData,
            canBeDeleted: !prepopData.isPrimary,
          }
        : null,
    });
    navigateTo("pages/address-details-edit/index");
  };

  const setDefaultAddress = async (id: number) => {
    const address = await setUserDefaultAddress(
      dispatchUserDataAction,
      userInfoState.userData!,
      {
        query: { id: id },
        authDispatch: dispatchAuthAction,
      }
    );
    if (address) {
      Taro.navigateBack();
    }
  };

  return (
    <Layout>
      <View className={style.wrapper}>
        <View className={style["address-details-wrapper"]}>
          <View className={style["listing"]}>
            <Header type="heading-l">
              {hasAddresses ? "配送信息" : "添加收货地址"}
            </Header>
            {hasAddresses ? (
              <RadioGroup
                //className={style["checkbox-group"]}
                onChange={(e) => {
                  if (e.detail.value) {
                    setDefaultAddress(e.detail.value);
                  }
                }}
              >
                {deliveryAddress &&
                  deliveryAddress.map((deliveryData) => {
                    return (
                      <View
                        key={deliveryData.id!}
                        className={style["clickable-card"]}
                      >
                        <View className={style["checkbox-grouping"]}>
                          <Radio
                            id={`${deliveryData.id}`}
                            value={`${deliveryData.id}`}
                            checked={deliveryData.isPrimary}
                          />
                          <View className={style["checkbox-bg"]} />
                          <View
                            className={style["checkbox-active"]}
                            style={{
                              opacity: deliveryData.isPrimary ? 1 : 0,
                            }}
                          />
                          <View className={style["address"]}>
                            <View className={style["top-row"]}>
                              <Label for={`${deliveryData.id}`}>
                                <View className={style.info}>
                                  {`${deliveryData.residenceArea.join("")}${
                                    deliveryData.address
                                  }`}
                                </View>
                              </Label>
                              <Icon
                                className={style.edit}
                                type="Edit"
                                onClick={() => {
                                  onDirectToEditClick(deliveryData);
                                }}
                              />
                            </View>
                            <Label
                              for={`${deliveryData.id}`}
                              className={style["bottom-row"]}
                            >
                              <View className={style["name"]}>
                                {deliveryData.name}
                              </View>
                              <View>{deliveryData.phone}</View>
                              <View className={style["default"]}>
                                {deliveryData.isPrimary ? "默认" : ""}
                              </View>
                            </Label>
                          </View>
                        </View>
                      </View>
                    );
                  })}
              </RadioGroup>
            ) : (
              // No addresses in user account
              <>
                <View
                  className={style["clickable-card"]}
                  onClick={() => {
                    onDirectToEditClick();
                  }}
                >
                  <View className={style["top-row"]}>
                    <View>手动添加配送地址</View>
                    <Icon className={style.arrow} type="Arrow" />
                  </View>
                </View>
                <View
                  className={style["clickable-card"]}
                  onClick={requestWechatAddress}
                >
                  <View className={style["top-row"]}>
                    <WeChatCta />
                    <Icon className={style.arrow} type="Arrow" />
                  </View>
                </View>
              </>
            )}
          </View>

          {/* Only buttons at bottom in case there are addresses */}
          {hasAddresses && (
            <View className={style["bottom-cta-wrapper"]}>
              <AbstractButton
                className={style["cta-sizing"]}
                color="dark"
                onClick={() => {
                  onDirectToEditClick();
                }}
              >
                添加收货地址
              </AbstractButton>
              <View
                className={style["wechat-sizing"]}
                onClick={requestWechatAddress}
              >
                <WeChatCta />
              </View>
            </View>
          )}
        </View>
      </View>
    </Layout>
  );
}
